package util;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Validator {
	public static final int NUM = 1;
	public static final int DATE = 2;
	public static final int CARID = 3;
	
	public static boolean isEmpty(String str) {
		if (str == null) return true;
		if ("".equals(str.trim())) return true;
		return false;
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}
	
	public static void bind(JTextField input, int type) {
		input.setInputVerifier(new InputVerifier() {

			@Override
			public boolean verify(JComponent input) {
				JTextField tf = (JTextField) input;
				String str = tf.getText();
				if (Validator.isEmpty(str)) {
					return true;
				}
				switch (type) {
				case Validator.NUM:
					if (str.matches("^\\d+$")) {
						return true;
					}
					JOptionPane.showMessageDialog(null, "请输入整数！");
					return false;
				case Validator.DATE:
					if (str.matches("^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$")) {
						return true;
					}
					JOptionPane.showMessageDialog(null, "请输入日期，形如2000-01-01！");
					return false;
				case Validator.CARID:
					if (str.matches(
							"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$")) {
						return true;
					}
					JOptionPane.showMessageDialog(null, "请输入车牌号码，形如京A12345！");
					return false;
				}
				return false;
			}
		});
	}

}
